package com.zhouxianglh.p34;

import java.util.Arrays;

/**
 * 34. 在排序数组中查找元素的第一个和最后一个位置
 * <p>
 * 二分法的使用,另外,可以用二分法查出两个分界效率更高
 *
 * @author zhouxianglh
 */
public class Solution {
    public static void main(String[] args) {
        // System.out.println(Arrays.toString(searchRange(new int[]{5, 7, 7, 8, 8, 10}, 8)));
        // System.out.println(Arrays.toString(searchRange(new int[]{5, 7, 7, 8, 8, 10}, 6)));
        System.out.println(Arrays.toString(searchRange(new int[]{1, 4}, 4)));
    }

    public static int[] searchRange(int[] nums, int target) {
        if (nums.length == 0) {
            return new int[]{-1, -1};
        }
        if (nums.length == 1) {
            if (nums[0] == target) {
                return new int[]{0, 0};
            } else {
                return new int[]{-1, -1};
            }
        }

        int start = 0;
        int end = nums.length - 1;
        int dist = -1;
        while (end >= start) {
            int mid = (end + start) >>> 1;
            if (nums[mid] > target) {
                end = mid - 1;
            } else if (nums[mid] < target) {
                start = mid + 1;
            } else {
                dist = mid;
                break;
            }
        }
        //
        if (dist == -1) {
            return new int[]{-1, -1};
        }
        //
        int resultStart = dist;
        int resultEnd = dist;
        while (resultStart > 0) {
            if (nums[resultStart] == nums[resultStart - 1]) {
                resultStart--;
            } else {
                break;
            }
        }
        while (resultEnd < nums.length - 1) {
            if (nums[resultEnd] == nums[resultEnd + 1]) {
                resultEnd++;
            } else {
                break;
            }
        }
        return new int[]{resultStart, resultEnd};
    }
}
